package battle.gameplay;

import com.jme3.bullet.collision.shapes.BoxCollisionShape;
import com.jme3.bullet.control.PhysicsGhostControl;
import com.jme3.bullet.nodes.PhysicsGhostNode;
import com.jme3.effect.EmitterPointShape;
import com.jme3.effect.EmitterSphereShape;
import com.jme3.effect.ParticleEmitter;
import com.jme3.math.Vector3f;
import com.jme3.scene.Spatial;


public class Bullet extends PhysicsGhostNode{
	
	private Vector3f dir, loc;
	private ParticleEmitter fire, smoke, explosion, crack;
	private float fireTimer, smokeTimer, explosionTimer, crackTimer;
	private boolean dead;
	
	public Bullet(Spatial bulletModel, BoxCollisionShape bulletShape, Vector3f dir, Vector3f loc){
		super(bulletModel, bulletShape);
		move(loc).scale(0.5f);
		setCollisionGroup(PhysicsGhostControl.COLLISION_GROUP_03);
		addCollideWithGroup(PhysicsGhostControl.COLLISION_GROUP_02);
		setName("bullet");
		this.dir = dir;
		this.loc = loc;
	}
	
	public void setFireEffect(ParticleEmitter fire){
		fire.setShape(new EmitterPointShape(loc));
		fire.setStartVel(dir.mult(3));
		fireTimer = 0.3f;
		this.fire = fire;
	}
	
	public void setSmokeEffect(ParticleEmitter smoke){
		smoke.setShape(new EmitterPointShape(loc));
		smokeTimer = 1.4f;
		this.smoke = smoke;
	}
	
	public void setExplosionEffect(ParticleEmitter explosion){
		explosion.setShape(new EmitterSphereShape(loc, 1));
		explosion.setStartVel(dir.mult(2));
		this.explosion = explosion;
	}
	
	public void setCrackEffect(ParticleEmitter crack){
		crack.setShape(new EmitterSphereShape(loc, 1));
		crack.setStartVel(dir.mult(2));
		this.crack = crack;
	}
	
	public void bulletHit(){
		smokeTimer = 0;
//		if (smoke != null)
//			smoke.removeFromParent();
		move(0, -200, 0);
		dead = true;
	}
	
	public int getDirection(){
		return Direction.index(dir);
	}
	
	public boolean update(float tpf){
		if (fireTimer > 0)
			fireTimer -= tpf;
		else if (fireTimer < 0 && fire != null){
			fire.removeFromParent();
			fireTimer = 0;
		}
		if (smokeTimer > 0){
			smokeTimer -= tpf;
			smoke.setShape(new EmitterPointShape(loc));
		}
		else if (smokeTimer < 0 && smoke != null){
			smoke.removeFromParent();
			smokeTimer = 0;
		}
		if (explosionTimer > 0)
			explosionTimer -= tpf;
		else if (explosionTimer < 0 && explosion != null){
			explosion.removeFromParent();
			explosionTimer = 0;
		}
		if (crackTimer > 0)
			crackTimer -= tpf;
		else if (crackTimer < 0 && crack != null){
			crack.removeFromParent();
			crackTimer = 0;
		}
		if (dead){
			smoke.removeFromParent();
		}
		else {
			move(dir.mult(tpf * 30));
			loc = loc.add(dir.mult(tpf * 30));
		}
		return (dead && fireTimer == 0 && smokeTimer == 0 && explosionTimer == 0 && crackTimer == 0);
	}
}
